home *** CD-ROM | disk | FTP | other *** search
/ Amiga Format CD 43 / Amiga Format CD43 (1999)(Future Publishing)(GB)(Track 1 of 2)[!][issue 1999-09].iso / -serious- / programming / other / python-1.52 / lib / python1.5 / smtplib.py < prev    next >
Text File  |  1999-06-14  |  18KB  |  528 lines

  1. #! /usr/bin/env python
  2.  
  3. '''SMTP/ESMTP client class.
  4.  
  5. Author: The Dragon De Monsyne <dragondm@integral.org>
  6. ESMTP support, test code and doc fixes added by
  7.     Eric S. Raymond <esr@thyrsus.com>
  8. Better RFC 821 compliance (MAIL and RCPT, and CRLF in data)
  9.     by Carey Evans <c.evans@clear.net.nz>, for picky mail servers.
  10.    
  11. This was modified from the Python 1.5 library HTTP lib.
  12.  
  13. This should follow RFC 821 (SMTP) and RFC 1869 (ESMTP).
  14.  
  15. Notes:
  16.  
  17. Please remember, when doing ESMTP, that the names of the SMTP service
  18. extensions are NOT the same thing as the option keywords for the RCPT
  19. and MAIL commands!
  20.  
  21. Example:
  22.  
  23.   >>> import smtplib
  24.   >>> s=smtplib.SMTP("localhost")
  25.   >>> print s.help()
  26.   This is Sendmail version 8.8.4
  27.   Topics:
  28.       HELO    EHLO    MAIL    RCPT    DATA
  29.       RSET    NOOP    QUIT    HELP    VRFY
  30.       EXPN    VERB    ETRN    DSN
  31.   For more info use "HELP <topic>".
  32.   To report bugs in the implementation send email to
  33.       sendmail-bugs@sendmail.org.
  34.   For local information send email to Postmaster at your site.
  35.   End of HELP info
  36.   >>> s.putcmd("vrfy","someone@here")
  37.   >>> s.getreply()
  38.   (250, "Somebody OverHere <somebody@here.my.org>")
  39.   >>> s.quit()
  40. '''
  41.  
  42. import socket
  43. import string
  44. import re
  45. import rfc822
  46. import types
  47.  
  48. SMTP_PORT = 25
  49. CRLF="\r\n"
  50.  
  51. # Exception classes used by this module. 
  52. class SMTPException(Exception):
  53.     """Base class for all exceptions raised by this module."""
  54.  
  55. class SMTPServerDisconnected(SMTPException):
  56.     """Not connected to any SMTP server.
  57.  
  58.     This exception is raised when the server unexpectedly disconnects,
  59.     or when an attempt is made to use the SMTP instance before
  60.     connecting it to a server.
  61.     """
  62.  
  63. class SMTPResponseException(SMTPException):
  64.     """Base class for all exceptions that include an SMTP error code.
  65.  
  66.     These exceptions are generated in some instances when the SMTP
  67.     server returns an error code.  The error code is stored in the
  68.     `smtp_code' attribute of the error, and the `smtp_error' attribute
  69.     is set to the error message.
  70.     """
  71.  
  72.     def __init__(self, code, msg):
  73.         self.smtp_code = code
  74.         self.smtp_error = msg
  75.         self.args = (code, msg)
  76.  
  77. class SMTPSenderRefused(SMTPResponseException):
  78.     """Sender address refused.
  79.     In addition to the attributes set by on all SMTPResponseException
  80.     exceptions, this sets `sender' to the string that the SMTP refused
  81.     """
  82.  
  83.     def __init__(self, code, msg, sender):
  84.         self.smtp_code = code
  85.         self.smtp_error = msg
  86.         self.sender = sender
  87.         self.args = (code, msg, sender)
  88.  
  89. class SMTPRecipientsRefused(SMTPResponseException):
  90.     """All recipient  addresses refused.
  91.     The errors for each recipient are accessable thru the attribute
  92.     'recipients', which is a dictionary of exactly the same sort as 
  93.     SMTP.sendmail() returns.  
  94.     """
  95.  
  96.     def __init__(self, recipients):
  97.         self.recipients = recipients
  98.         self.args = ( recipients,)
  99.  
  100.  
  101.  
  102. class SMTPDataError(SMTPResponseException):
  103.     """The SMTP server didn't accept the data."""
  104.  
  105. class SMTPConnectError(SMTPResponseException):
  106.     """Error during connection establishment"""
  107.  
  108. class SMTPHeloError(SMTPResponseException):
  109.     """The server refused our HELO reply"""
  110.  
  111. def quoteaddr(addr):
  112.     """Quote a subset of the email addresses defined by RFC 821.
  113.  
  114.     Should be able to handle anything rfc822.parseaddr can handle.
  115.     """
  116.     m=None
  117.     try:
  118.         m=rfc822.parseaddr(addr)[1]
  119.     except AttributeError:
  120.         pass
  121.     if not m:
  122.         #something weird here.. punt -ddm
  123.         return addr
  124.     else:
  125.         return "<%s>" % m
  126.  
  127. def quotedata(data):
  128.     """Quote data for email.
  129.  
  130.     Double leading '.', and change Unix newline '\n', or Mac '\r' into
  131.     Internet CRLF end-of-line.
  132.     """
  133.     return re.sub(r'(?m)^\.', '..',
  134.         re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data))
  135.  
  136. class SMTP:
  137.     """This class manages a connection to an SMTP or ESMTP server.
  138.     SMTP Objects:
  139.         SMTP objects have the following attributes:    
  140.             helo_resp 
  141.                 This is the message given by the server in responce to the 
  142.                 most recent HELO command.
  143.                 
  144.             ehlo_resp
  145.                 This is the message given by the server in responce to the 
  146.                 most recent EHLO command. This is usually multiline.
  147.  
  148.             does_esmtp 
  149.                 This is a True value _after you do an EHLO command_, if the
  150.                 server supports ESMTP.
  151.  
  152.             esmtp_features 
  153.                 This is a dictionary, which, if the server supports ESMTP,
  154.                 will  _after you do an EHLO command_, contain the names of the
  155.                 SMTP service  extentions this server supports, and their 
  156.                 parameters (if any).
  157.                 Note, all extention names are mapped to lower case in the 
  158.                 dictionary. 
  159.  
  160.         For method docs, see each method's docstrings. In general, there is 
  161.             a method of the same name to perform each SMTP command, and there 
  162.             is a method called 'sendmail' that will do an entire mail 
  163.             transaction.
  164.     """
  165.     debuglevel = 0
  166.     file = None
  167.     helo_resp = None
  168.     ehlo_resp = None
  169.     does_esmtp = 0
  170.  
  171.     def __init__(self, host = '', port = 0):
  172.         """Initialize a new instance.
  173.  
  174.         If specified, `host' is the name of the remote host to which to
  175.         connect.  If specified, `port' specifies the port to which to connect.
  176.         By default, smtplib.SMTP_PORT is used.  An SMTPConnectError is
  177.         raised if the specified `host' doesn't respond correctly.
  178.  
  179.         """
  180.         self.esmtp_features = {}
  181.         if host:
  182.             (code, msg) = self.connect(host, port)
  183.             if code != 220:
  184.                 raise SMTPConnectError(code, msg)
  185.     
  186.     def set_debuglevel(self, debuglevel):
  187.         """Set the debug output level.
  188.  
  189.         A non-false value results in debug messages for connection and for all
  190.         messages sent to and received from the server.
  191.  
  192.         """
  193.         self.debuglevel = debuglevel
  194.  
  195.     def connect(self, host='localhost', port = 0):
  196.         """Connect to a host on a given port.
  197.  
  198.         If the hostname ends with a colon (`:') followed by a number, and
  199.         there is no port specified, that suffix will be stripped off and the
  200.         number interpreted as the port number to use.
  201.  
  202.         Note: This method is automatically invoked by __init__, if a host is
  203.         specified during instantiation.
  204.  
  205.         """
  206.         if not port:
  207.             i = string.find(host, ':')
  208.             if i >= 0:
  209.                 host, port = host[:i], host[i+1:]
  210.                 try: port = string.atoi(port)
  211.                 except string.atoi_error:
  212.                     raise socket.error, "nonnumeric port"
  213.         if not port: port = SMTP_PORT
  214.         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  215.         if self.debuglevel > 0: print 'connect:', (host, port)
  216.         self.sock.connect(host, port)
  217.         (code,msg)=self.getreply()
  218.         if self.debuglevel >0 : print "connect:", msg
  219.         return (code,msg)
  220.     
  221.     def send(self, str):
  222.         """Send `str' to the server."""
  223.         if self.debuglevel > 0: print 'send:', `str`
  224.         if self.sock:
  225.             try:
  226.                 self.sock.send(str)
  227.             except socket.error:
  228.                 raise SMTPServerDisconnected('Server not connected')
  229.         else:
  230.             raise SMTPServerDisconnected('please run connect() first')
  231.  
  232.     def putcmd(self, cmd, args=""):
  233.         """Send a command to the server."""
  234.         str = '%s %s%s' % (cmd, args, CRLF)
  235.         self.send(str)
  236.     
  237.     def getreply(self):
  238.         """Get a reply from the server.
  239.         
  240.         Returns a tuple consisting of:
  241.  
  242.           - server response code (e.g. '250', or such, if all goes well)
  243.             Note: returns -1 if it can't read response code.
  244.  
  245.           - server response string corresponding to response code (multiline
  246.             responses are converted to a single, multiline string).
  247.  
  248.         Raises SMTPServerDisconnected if end-of-file is reached.
  249.         """
  250.         resp=[]
  251.         if self.file is None:
  252.             self.file = self.sock.makefile('rb')
  253.         while 1:
  254.             line = self.file.readline()
  255.             if line == '':
  256.                 self.close()
  257.                 raise SMTPServerDisconnected("Connection unexpectedly closed")
  258.             if self.debuglevel > 0: print 'reply:', `line`
  259.             resp.append(string.strip(line[4:]))
  260.             code=line[:3]
  261.             # Check that the error code is syntactically correct.
  262.             # Don't attempt to read a continuation line if it is broken.
  263.             try:
  264.                 errcode = string.atoi(code)
  265.             except ValueError:
  266.                 errcode = -1
  267.                 break
  268.             # Check if multiline response.
  269.             if line[3:4]!="-":
  270.                 break
  271.  
  272.         errmsg = string.join(resp,"\n")
  273.         if self.debuglevel > 0: 
  274.             print 'reply: retcode (%s); Msg: %s' % (errcode,errmsg)
  275.         return errcode, errmsg
  276.     
  277.     def docmd(self, cmd, args=""):
  278.         """Send a command, and return its response code."""
  279.         self.putcmd(cmd,args)
  280.         return self.getreply()
  281.  
  282.     # std smtp commands
  283.     def helo(self, name=''):
  284.         """SMTP 'helo' command.
  285.         Hostname to send for this command defaults to the FQDN of the local
  286.         host.
  287.         """
  288.         name=string.strip(name)
  289.         if len(name)==0:
  290.             name=socket.gethostbyaddr(socket.gethostname())[0]
  291.         self.putcmd("helo",name)
  292.         (code,msg)=self.getreply()
  293.         self.helo_resp=msg
  294.         return (code,msg)
  295.  
  296.     def ehlo(self, name=''):
  297.         """ SMTP 'ehlo' command.
  298.         Hostname to send for this command defaults to the FQDN of the local
  299.         host.
  300.         """
  301.         name=string.strip(name)
  302.         if len(name)==0:
  303.             name=socket.gethostbyaddr(socket.gethostname())[0]
  304.         self.putcmd("ehlo",name)
  305.         (code,msg)=self.getreply()
  306.         # According to RFC1869 some (badly written) 
  307.         # MTA's will disconnect on an ehlo. Toss an exception if 
  308.         # that happens -ddm
  309.         if code == -1 and len(msg) == 0:
  310.             raise SMTPServerDisconnected("Server not connected")
  311.         self.ehlo_resp=msg
  312.         if code<>250:
  313.             return (code,msg)
  314.         self.does_esmtp=1
  315.         #parse the ehlo responce -ddm
  316.         resp=string.split(self.ehlo_resp,'\n')
  317.         del resp[0]
  318.         for each in resp:
  319.             m=re.match(r'(?P<feature>[A-Za-z0-9][A-Za-z0-9\-]*)',each)
  320.             if m:
  321.                 feature=string.lower(m.group("feature"))
  322.                 params=string.strip(m.string[m.end("feature"):])
  323.                 self.esmtp_features[feature]=params
  324.         return (code,msg)
  325.  
  326.     def has_extn(self, opt):
  327.         """Does the server support a given SMTP service extension?"""
  328.         return self.esmtp_features.has_key(string.lower(opt))
  329.  
  330.     def help(self, args=''):
  331.         """SMTP 'help' command.
  332.         Returns help text from server."""
  333.         self.putcmd("help", args)
  334.         return self.getreply()
  335.  
  336.     def rset(self):
  337.         """SMTP 'rset' command -- resets session."""
  338.         return self.docmd("rset")
  339.  
  340.     def noop(self):
  341.         """SMTP 'noop' command -- doesn't do anything :>"""
  342.         return self.docmd("noop")
  343.  
  344.     def mail(self,sender,options=[]):
  345.         """SMTP 'mail' command -- begins mail xfer session."""
  346.         optionlist = ''
  347.         if options and self.does_esmtp:
  348.             optionlist = string.join(options, ' ')
  349.         self.putcmd("mail", "FROM:%s %s" % (quoteaddr(sender) ,optionlist))
  350.         return self.getreply()
  351.  
  352.     def rcpt(self,recip,options=[]):
  353.         """SMTP 'rcpt' command -- indicates 1 recipient for this mail."""
  354.         optionlist = ''
  355.         if options and self.does_esmtp:
  356.             optionlist = ' ' + string.join(options, ' ')
  357.         self.putcmd("rcpt","TO:%s%s" % (quoteaddr(recip),optionlist))
  358.         return self.getreply()
  359.  
  360.     def data(self,msg):
  361.         """SMTP 'DATA' command -- sends message data to server. 
  362.  
  363.         Automatically quotes lines beginning with a period per rfc821.
  364.         Raises SMTPDataError if there is an unexpected reply to the
  365.         DATA command; the return value from this method is the final
  366.         response code received when the all data is sent.
  367.         """
  368.         self.putcmd("data")
  369.         (code,repl)=self.getreply()
  370.         if self.debuglevel >0 : print "data:", (code,repl)
  371.         if code <> 354:
  372.             raise SMTPDataError(code,repl)
  373.         else:
  374.             self.send(quotedata(msg))
  375.             self.send("%s.%s" % (CRLF, CRLF))
  376.             (code,msg)=self.getreply()
  377.             if self.debuglevel >0 : print "data:", (code,msg)
  378.             return (code,msg)
  379.  
  380.     def verify(self, address):
  381.         """SMTP 'verify' command -- checks for address validity."""
  382.         self.putcmd("vrfy", quoteaddr(address))
  383.         return self.getreply()
  384.     # a.k.a.
  385.     vrfy=verify
  386.  
  387.     def expn(self, address):
  388.         """SMTP 'verify' command -- checks for address validity."""
  389.         self.putcmd("expn", quoteaddr(address))
  390.         return self.getreply()
  391.  
  392.     # some useful methods
  393.     def sendmail(self, from_addr, to_addrs, msg, mail_options=[],
  394.                  rcpt_options=[]): 
  395.         """This command performs an entire mail transaction. 
  396.  
  397.         The arguments are: 
  398.             - from_addr    : The address sending this mail.
  399.             - to_addrs     : A list of addresses to send this mail to.  A bare
  400.                              string will be treated as a list with 1 address.
  401.             - msg          : The message to send. 
  402.             - mail_options : List of ESMTP options (such as 8bitmime) for the
  403.                              mail command.
  404.             - rcpt_options : List of ESMTP options (such as DSN commands) for
  405.                              all the rcpt commands.
  406.  
  407.         If there has been no previous EHLO or HELO command this session, this
  408.         method tries ESMTP EHLO first.  If the server does ESMTP, message size
  409.         and each of the specified options will be passed to it.  If EHLO
  410.         fails, HELO will be tried and ESMTP options suppressed.
  411.  
  412.         This method will return normally if the mail is accepted for at least
  413.         one recipient. It returns a dictionary, with one entry for each
  414.         recipient that was refused.  Each entry contains a tuple of
  415.         the SMTP error code and the accompanying error message sent by
  416.         the server.
  417.  
  418.         This method may raise the following exceptions:
  419.  
  420.          SMTPHeloError          The server didn't reply properly to
  421.                                 the helo greeting. 
  422.          SMTPRecipientsRefused  The server rejected for ALL recipients
  423.                                 (no mail was sent).
  424.          SMTPSenderRefused      The server didn't accept the from_addr.
  425.          SMTPDataError          The server replied with an unexpected
  426.                                 error code (other than a refusal of
  427.                                 a recipient).
  428.  
  429.         Note: the connection will be open even after an exception is raised.
  430.  
  431.         Example:
  432.       
  433.          >>> import smtplib
  434.          >>> s=smtplib.SMTP("localhost")
  435.          >>> tolist=["one@one.org","two@two.org","three@three.org","four@four.org"]
  436.          >>> msg = '''
  437.          ... From: Me@my.org
  438.          ... Subject: testin'...
  439.          ...
  440.          ... This is a test '''
  441.          >>> s.sendmail("me@my.org",tolist,msg)
  442.          { "three@three.org" : ( 550 ,"User unknown" ) }
  443.          >>> s.quit()
  444.         
  445.         In the above example, the message was accepted for delivery to three
  446.         of the four addresses, and one was rejected, with the error code
  447.         550. If all addresses are accepted, then the method will return an
  448.         empty dictionary.
  449.  
  450.         """
  451.         if self.helo_resp is None and self.ehlo_resp is None:
  452.             if not (200 <= self.ehlo()[0] <= 299):
  453.                 (code,resp) = self.helo()
  454.                 if not (200 <= code <= 299):
  455.                     raise SMTPHeloError(code, resp)
  456.         esmtp_opts = []
  457.         if self.does_esmtp:
  458.             # Hmmm? what's this? -ddm
  459.             # self.esmtp_features['7bit']=""
  460.             if self.has_extn('size'):
  461.                 esmtp_opts.append("size=" + `len(msg)`)
  462.             for option in mail_options:
  463.                 esmtp_opts.append(option)
  464.  
  465.         (code,resp) = self.mail(from_addr, esmtp_opts)
  466.         if code <> 250:
  467.             self.rset()
  468.             raise SMTPSenderRefused(code, resp, from_addr)
  469.         senderrs={}
  470.         if type(to_addrs) == types.StringType:
  471.             to_addrs = [to_addrs]
  472.         for each in to_addrs:
  473.             (code,resp)=self.rcpt(each, rcpt_options)
  474.             if (code <> 250) and (code <> 251):
  475.                 senderrs[each]=(code,resp)
  476.         if len(senderrs)==len(to_addrs):
  477.             # the server refused all our recipients
  478.             self.rset()
  479.             raise SMTPRecipientsRefused(senderrs)
  480.         (code,resp)=self.data(msg)
  481.         if code <> 250:
  482.             self.rset()
  483.             raise SMTPDataError(code, resp)
  484.         #if we got here then somebody got our mail
  485.         return senderrs         
  486.  
  487.  
  488.     def close(self):
  489.         """Close the connection to the SMTP server."""
  490.         if self.file:
  491.             self.file.close()
  492.         self.file = None
  493.         if self.sock:
  494.             self.sock.close()
  495.         self.sock = None
  496.  
  497.  
  498.     def quit(self):
  499.         """Terminate the SMTP session."""
  500.         self.docmd("quit")
  501.         self.close()
  502.  
  503.  
  504. # Test the sendmail method, which tests most of the others.
  505. # Note: This always sends to localhost.
  506. if __name__ == '__main__':
  507.     import sys, rfc822
  508.  
  509.     def prompt(prompt):
  510.         sys.stdout.write(prompt + ": ")
  511.         return string.strip(sys.stdin.readline())
  512.  
  513.     fromaddr = prompt("From")
  514.     toaddrs  = string.splitfields(prompt("To"), ',')
  515.     print "Enter message, end with ^D:"
  516.     msg = ''
  517.     while 1:
  518.         line = sys.stdin.readline()
  519.         if not line:
  520.             break
  521.         msg = msg + line
  522.     print "Message length is " + `len(msg)`
  523.  
  524.     server = SMTP('localhost')
  525.     server.set_debuglevel(1)
  526.     server.sendmail(fromaddr, toaddrs, msg)
  527.     server.quit()
  528.